﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using VanTaiBLL;
using VanTaiData;
using VanTaiProperty;
using Roles;
using System.Web.UI.HtmlControls;

namespace VanTaiTMS.Page
{
    public partial class quan_ly_hang_hoa : System.Web.UI.Page
    {
        #region[Define]
        private DataTable dtDO;
        private DataTable dtDOLine;
        private DataTable dtDO_Detail_Edit;
        private DataTable dtUnit;
        private DataTable dtSearch;
        private DataTable dtCusomer;
        private DataTable dtdriver;
        private DataTable dtCarNo;
        protected string SuggestionList;
        protected string StrAlert = "";
        private DataTable dtAutoComplete;
        private static bool flag = false;
        private clsTMDOBusiness clsDO = new clsTMDOBusiness();
        private ClsTmUnitBusiness clsUnit = new ClsTmUnitBusiness();
        private TMDoNew_BusinessLogic clsDoNew = new TMDoNew_BusinessLogic();
        private clsTMCustomersBusiness clsCustomer = new clsTMCustomersBusiness();
        private clsTMMemberBusiness clsMember = new clsTMMemberBusiness();
        private clsTMVehicleBusiness clsCarNo = new clsTMVehicleBusiness();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermisstion();
            Autocomplate();
            if (!IsPostBack)
            {
                BindGridUnit();
                BindGridDO();
            }
        }
        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            flag = true;
            lbThongBaoLoi.Text = "";
            txtMaHangHoa.Enabled = true;
            ClearTextBox();
            OpenDialog("#danhmuchanghoa");
            imgSave.ToolTip = "Thêm mới";
            upNewUpdatePanel.Update();
            imgSave.Visible = true;
        }
        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            lbThongBaoLoi.Text = "";
            txtMaHangHoa.Enabled = false;
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkView != null)
                {
                    if (chkView.Checked)
                    {
                        BindGridDO_Detail_Edit(Convert.ToInt32(ListViewAll.DataKeys[i].Value.ToString()));
                        OpenDialog("#danhmuchanghoa");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
        }
        protected void cmdDel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkHide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkHide != null)
                {
                    if (chkHide.Checked)
                    {
                        try
                        {
                            VanTaiBLL.TMDoNew_BusinessLogic.DeleteTMDoNew(int.Parse(ListViewAll.DataKeys[i].Value.ToString()));
                        }
                        catch
                        {
                            lbThongBaoXoa.Text = "Mẫu tin vẩn còn tồn tại !";
                            OpenDialog("#thongbaoxoa");
                            upDatePanelThongBaoXoa.Update();
                            cmdAgree.Visible = false;
                            cmdClose.Text = "Đóng lại";
                        }
                    }
                }
            }
            BindGridDO();
        }
        protected void cmdSerach_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                StrAlert += "<div class='alert alert-warning'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Vui lòng nhập vào từ khoá để tìm kiếm !";
                StrAlert += "</div>";
            }
            else
            {
                Search(txtSearch.Text);
            }
        }
        protected void cmdRefesh_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
            BindGridDO();
        }
        //-------------------List-View-----------------------
        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                HttpCookie cookie = Request.Cookies["UserLogin"];
                bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyHangHoa, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                lbThongBaoLoi.Text = "";
                txtMaHangHoa.Enabled = false;
                if (e.CommandName == "Accept")
                {
                    if (Edit == false)
                    {
                        imgSave.Visible = false;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridDoLine(SenderId);
                    }
                    else
                    {
                        imgSave.Visible = true;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridDoLine(SenderId);
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void ListViewAll_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                LinkButton linkListName = (LinkButton)e.Item.FindControl("linkListName");
                LinkButton linkListName_E = (LinkButton)e.Item.FindControl("linkListName_E");
                string _jsDouble1 = ClientScript.GetPostBackClientHyperlink(linkListName, "");
            }
        }
        //-------------------Data-Pagger---------------------
        protected void DataPagerListAll_PreRender(object sender, EventArgs e)
        {
            DataPagerListAll.PageSize = 5;
            BindGridDO();
        }
        //-------------------Button-Popup--------------------
        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            if (txtMaHangHoa.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào mã phiếu !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtTenHangHoa.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào chứng từ !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drKhachHang.SelectedValue == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn khách hàng !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drSoXe.SelectedValue == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn số xe !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drTaiXe.SelectedValue == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn tài xế !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtMaHangHoa.Text != "" && txtTenHangHoa.Text != "" && drKhachHang.SelectedValue.ToString() != "-1" && drSoXe.SelectedValue.ToString() != "-1" && drTaiXe.SelectedValue.ToString() != "-1")
            {
                Insert();
            }
        }
        protected void imgrefesh_Click(object sender, ImageClickEventArgs e)
        {

        }
        protected void cmdAgree_Click(object sender, EventArgs e)
        {
            
        }
        protected void cmdClose_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbaoxoa");
        }
        protected void cmdCloseThongBao_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbao");
        }
        #endregion

        #region[Function]
        protected void BindGridDO()
        {
            dtDO = clsDoNew.Search(txtSearch.Text);
            if (dtDO != null && dtDO.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtDO;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
            }
        }
        protected void BindGridDO_Detail_Edit(int id)
        {
            dtDO_Detail_Edit = clsDoNew.GetDataDetailEdit(id);
            if (dtDO_Detail_Edit != null && dtDO_Detail_Edit.Rows.Count > 0)
            {
                lbID.Text = dtDO_Detail_Edit.Rows[0]["RowID"].ToString();
                lbIDXoa.Text = dtDO_Detail_Edit.Rows[0]["RowID"].ToString();
                txtMaHangHoa.Text = dtDO_Detail_Edit.Rows[0]["No_"].ToString();
                txtTenHangHoa.Text = dtDO_Detail_Edit.Rows[0]["DocumentNo"].ToString();
                txtKhachHang.Text = dtDO_Detail_Edit.Rows[0]["CustomerNo"].ToString();
                txtCarNo.Text = dtDO_Detail_Edit.Rows[0]["CarNo"].ToString();
                txtTaiXe.Text = dtDO_Detail_Edit.Rows[0]["Driver"].ToString();
                txtSealNo.Text = dtDO_Detail_Edit.Rows[0]["SealNo"].ToString();
                txtFoundation.Text = dtDO_Detail_Edit.Rows[0]["Foundation"].ToString();
                txtLocationNo.Text = dtDO_Detail_Edit.Rows[0]["LocationNo"].ToString();
                txtContainer.Text = dtDO_Detail_Edit.Rows[0]["Container"].ToString();
                txtShip.Text = dtDO_Detail_Edit.Rows[0]["Ship"].ToString();
                txtReason.Text = dtDO_Detail_Edit.Rows[0]["Reason"].ToString();
                txtCarryExportType.Text = dtDO_Detail_Edit.Rows[0]["CarryExportType"].ToString();
                txtEmployeeNo.Text = dtDO_Detail_Edit.Rows[0]["EmployeeNo"].ToString();
                txtGhiChu.Text = dtDO_Detail_Edit.Rows[0]["Description"].ToString();
            }
        }
        protected void BindGridDoLine(string id)
        {
            dtDOLine = clsDoNew.GetDataDetailLine(id);
            if (dtDOLine != null && dtDOLine.Rows.Count > 0)
            {
                ListViewDetail.DataSource = dtDOLine;
                ListViewDetail.DataBind();
                ListViewDetail.Visible = true;
            }
            else
            {
                ListViewDetail.Visible = false;
            }
        }
        protected void BindGridUnit()
        {
            dtCusomer = clsCustomer.BindGirdTMCustomers();
            dtCarNo = clsCarNo.BindGirdTMVehicle();
            dtdriver = clsMember.BindGirdTMMember();
            if (dtCusomer != null && dtCusomer.Rows.Count > 0)
            {
                drKhachHang.DataSource = dtCusomer;
                drKhachHang.DataTextField = "Customers_Name";
                drKhachHang.DataValueField = "Customers_ID";
                drKhachHang.DataBind();
            }
            if (dtCarNo != null && dtCarNo.Rows.Count > 0)
            {
                drSoXe.DataSource = dtCarNo;
                drSoXe.DataTextField = "Vehicle_Number";
                drSoXe.DataValueField = "Vehicle_ID";
                drSoXe.DataBind();
            }
            if (dtdriver != null && dtdriver.Rows.Count > 0)
            {
                drTaiXe.DataSource = dtdriver;
                drTaiXe.DataValueField = "Member_ID";
                drTaiXe.DataValueField = "FullNameMem";
                drTaiXe.DataBind();
            }
        }
        protected void Insert()
        {
            //Insert
            if (flag)
            {
                InsertDO();
            }
            else//Update
            {
                if (clsDO.TMDO_Check_Delete_TMDO_BILL(int.Parse(lbIDXoa.Text)) == false)
                {
                    UpdateDO();
                }
                else
                {
                    lbThongBaoLoi.Text = "Hàng hoá này đang trong quá trình xuất hàng.Không thể thay đổi thông tin !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            dtDO = clsDoNew.GetData();
            if (dtDO != null && dtDO.Rows.Count > 0)
            {
                foreach (DataRow dr in dtDO.Rows)
                {
                    if (txtTenHangHoa.Text == dr["No_"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void InsertDO()
        {
            try
            {
                if (CheckInsert())
                {
                    lbThongBaoLoi.Text = "Mã hàng hoá này đã tồn tại xe này đã tồn tại !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
                else
                {
                    VanTaiProperty.clsTMDoNewProperty obj = new clsTMDoNewProperty();
                    obj.No_ = txtMaHangHoa.Text;
                    obj.DocumentNo = txtTenHangHoa.Text;
                    obj.CustomerNo = drKhachHang.SelectedValue.ToString();
                    obj.PostingDate = DateTime.Today;
                    obj.DocumentDate = DateTime.Today;
                    obj.DocumentTime = DateTime.Today;
                    obj.Receiver = txtReceiver.Text;
                    obj.CarNo = drSoXe.SelectedValue.ToString();
                    obj.Driver = drTaiXe.SelectedValue.ToString();
                    obj.SealNo = txtSealNo.Text;
                    obj.Foundation = txtFoundation.Text;
                    obj.FoundationDate = DateTime.Today;
                    obj.LocationNo = txtLocationNo.Text;
                    obj.Container = txtContainer.Text;
                    obj.Ship = txtShip.Text;
                    obj.Reason = txtReason.Text;
                    obj.CarryExportType = 0;
                    obj.EmployeeNo = txtEmployeeNo.Text;
                    obj.Status = 0;
                    obj.Description = txtGhiChu.Text;
                    obj.UserID = string.Empty;
                    VanTaiBLL.TMDoNew_BusinessLogic.InsertTMDoNew(obj);
                    lbThongBaoLoi.Text = "Thêm mẫu tin thành công !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                    BindGridDO();
                    ClearTextBox();
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void UpdateDO()
        {
            try
            {
                VanTaiProperty.clsTMDoNewProperty obj = new clsTMDoNewProperty();
                obj.RowID = int.Parse(lbID.Text);
                obj.No_ = txtMaHangHoa.Text;
                obj.DocumentNo = txtTenHangHoa.Text;
                obj.CustomerNo = drKhachHang.SelectedValue.ToString();
                obj.PostingDate = DateTime.Today;
                obj.DocumentDate = DateTime.Today;
                obj.DocumentTime = DateTime.Today;
                obj.Receiver = txtReceiver.Text;
                obj.CarNo = drSoXe.SelectedValue.ToString();
                obj.Driver = drTaiXe.SelectedValue.ToString();
                obj.SealNo = txtSealNo.Text;
                obj.Foundation = txtFoundation.Text;
                obj.FoundationDate = DateTime.Today;
                obj.LocationNo = txtLocationNo.Text;
                obj.Container = txtContainer.Text;
                obj.Ship = txtShip.Text;
                obj.Reason = txtReason.Text;
                obj.CarryExportType = int.Parse(txtCarryExportType.Text);
                obj.EmployeeNo = txtEmployeeNo.Text;
                obj.Status = 0;
                obj.Description = txtGhiChu.Text;
                obj.UserID = string.Empty;
                VanTaiBLL.TMDoNew_BusinessLogic.UpdateTMDoNew(obj);
                lbThongBaoLoi.Text = "Cập nhật mẫu tin thành công !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
                BindGridDO();
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        //AutoComplate
        protected void Autocomplate()
        {
            dtAutoComplete = clsDoNew.GetData();
            if (dtAutoComplete != null && dtAutoComplete.Rows.Count > 0)
            {
                foreach (DataRow dr in dtAutoComplete.Rows)
                {
                    if (string.IsNullOrEmpty(SuggestionList))
                    {
                        SuggestionList += "\"" + dr["No_"].ToString().Replace("\n", " ") + "\",";
                    }
                    else
                    {
                        SuggestionList += "\"" + dr["No_"].ToString().Replace("\n", " ") + "\",";
                    }
                }
            }
        }
        protected void Search(string keywords)
        {
            dtSearch = clsDoNew.Search(keywords);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtSearch;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;

                StrAlert += "<div class='alert alert-success'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Tìm thấy " + dtSearch.Rows.Count.ToString() + " mẫu tin !";
                StrAlert += "</div>";
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }
        #endregion

        #region[OpenDialog]
        private void OpenDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        private void CloseDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('close');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        #endregion

        #region[ClearTexBox]
        protected void ClearTextBox()
        {
            txtMaHangHoa.Text = string.Empty;
            txtTenHangHoa.Text = string.Empty;
            txtDocumentNo.Text = string.Empty;
            txtKhachHang.Text = string.Empty;
            txtCarNo.Text = string.Empty;
            txtTaiXe.Text = string.Empty;
            txtSealNo.Text = string.Empty;
            txtFoundation.Text = string.Empty;
            txtLocationNo.Text = string.Empty;
            txtContainer.Text = string.Empty;
            txtShip.Text = string.Empty;
            txtReason.Text = string.Empty;
            txtCarryExportType.Text = string.Empty;
            txtEmployeeNo.Text = string.Empty;
            txtGhiChu.Text = string.Empty;

            drKhachHang.SelectedIndex = -1;
            drSoXe.SelectedIndex = -1;
            drTaiXe.SelectedIndex = -1;
        }
        #endregion

        #region[Permisstion]
        protected void CheckPermisstion()
        {
            HttpCookie cookie = Request.Cookies["UserLogin"];
            if (cookie != null)
            {
                bool Is_Page_All = SecurityServices.HasPermisstionPage(StringContent.QuanLyHangHoa, int.Parse(cookie["RolesID"]), true);
                if (Is_Page_All == true)
                {
                    bool AddNew = SecurityServices.HasPermisstion(StringContent.QuanLyHangHoa, int.Parse(cookie["RolesID"]), TypeaAudit.AddNew);
                    if (AddNew == false)
                    {
                        cmdAddNew.Visible = false;
                    }
                    else
                    {
                        cmdAddNew.Visible = true;
                    }
                    bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyHangHoa, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                    if (Edit == false)
                    {
                        cmdEdit.Visible = false;
                    }
                    else
                    {
                        cmdEdit.Visible = true;
                    }
                    bool Del = SecurityServices.HasPermisstion(StringContent.QuanLyHangHoa, int.Parse(cookie["RolesID"]), TypeaAudit.Delete);
                    if (Del == false)
                    {
                        cmdDel.Visible = false;
                    }
                    else
                    {
                        cmdDel.Visible = true;
                    }
                }
                else
                {
                    Response.Redirect("error-page.aspx");
                }
            }
        }
        #endregion
    }
}